<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <!-- 基本信息 -->
    <el-descriptions :column="2" border class="mb-4">
      <el-descriptions-item label="租户">
        {{ tenantNameMap[detail?.rechargeTenantId] ?? detail?.rechargeTenantId ?? '-' }}
      </el-descriptions-item>
      <el-descriptions-item label="过滤网关">
        {{ detail?.filterName ?? '-' }}
      </el-descriptions-item>
      <el-descriptions-item label="密钥">
        {{ detail?.appSecret ?? '-' }}
      </el-descriptions-item>

      <!-- 产品权限 -->
      <el-descriptions-item label="产品权限">
        {{ formatProductPermissions(detail?.productPermissions) }}
      </el-descriptions-item>

      <el-descriptions-item label="当前余额(元)">
        {{ formatMoney(detail?.balance) }}
      </el-descriptions-item>
      <el-descriptions-item label="到期时间">
        <span v-if="detail?.expireTime">{{ renderExpire(detail?.expireTime) }}</span>
        <span v-else>-</span>
      </el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="detail?.enabled ? 'success' : 'info'">
          {{ detail?.enabled ? '启用' : '停用' }}
        </el-tag>
      </el-descriptions-item>
    </el-descriptions>

    <!-- 充值表单 -->
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
      <el-form-item label="充值金额(元)" prop="amount">
        <el-input-number
            v-model="formData.amount"
            :min="0.01"
            :step="0.01"
            :precision="2"
            controls-position="right"
            class="!w-260px"
            placeholder="请输入充值金额"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
            v-model="formData.remark"
            placeholder="可填写本次充值备注"
            maxlength="200"
            show-word-limit
            type="text"
            class="!w-380px"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" :loading="submitting" @click="onSubmit">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { SecretAccountApi } from '@/api/vos/secretaccount'
import * as TenantApi from '@/api/system/tenant'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'

defineOptions({ name: 'SecretAccountRechargeForm' })

const message = useMessage()
const dialogVisible = ref(false)
const dialogTitle = ref('充值')
const submitting = ref(false)
const currentId = ref<number | null>(null)

/** 字典：产品权限 */
const reqTypeOptions = getStrDictOptions(DICT_TYPE.REQUEST_TYPE)
const reqTypeMap: Record<string, string> = {}
reqTypeOptions.forEach((d: any) => (reqTypeMap[String(d.value)] = d.label))

/** 详情与租户名 */
const detail = ref<any>(null)
const tenantNameMap = reactive<Record<number, string>>({})

/** 表单 */
const formRef = ref()
const formData = reactive<{ amount: number | undefined; remark: string | undefined }>({
  amount: undefined,
  remark: undefined
})
const formRules = {
  amount: [
    { required: true, message: '请输入充值金额', trigger: ['blur', 'change'] },
    {
      validator: (_: any, val: any, cb: any) => {
        const n = Number(val)
        if (Number.isNaN(n) || n <= 0) return cb(new Error('金额必须大于 0'))
        cb()
      },
      trigger: ['blur', 'change']
    }
  ]
}

/** 工具函数 */
const formatMoney = (v: any) => {
  if (v === null || v === undefined || v === '') return '0.00'
  const n = Number(v)
  if (Number.isNaN(n)) return String(v)
  return n.toFixed(2)
}
const renderExpire = (raw: any) => {
  if (typeof raw === 'number') {
    const ms = raw < 1e12 ? raw * 1000 : raw
    return dayjs(ms).format('YYYY-MM-DD HH:mm:ss')
  }
  if (typeof raw === 'string' && /^\d{10,13}$/.test(raw)) {
    const n = Number(raw)
    const ms = raw.length === 10 ? n * 1000 : n
    return dayjs(ms).format('YYYY-MM-DD HH:mm:ss')
  }
  return dayjs(raw).isValid() ? dayjs(raw).format('YYYY-MM-DD HH:mm:ss') : raw
}
const formatProductPermissions = (val: any) => {
  if (!val) return '-'
  const codes = String(val).split(',').map((s) => s.trim()).filter(Boolean)
  if (!codes.length) return '-'
  const labels = codes.map((c) => reqTypeMap[c] ?? c)
  return labels.join('、')
}

/** 数据加载 */
const loadTenants = async () => {
  const res = await TenantApi.getTenantList()
  const arr = Array.isArray(res) ? res : (res?.list ?? [])
  arr.forEach((it: any) => {
    const tid = Number(it.id)
    if (!Number.isNaN(tid)) tenantNameMap[tid] = it.name || `租户#${tid}`
  })
}
const loadDetail = async (id: number) => {
  const d = await SecretAccountApi.getSecretAccount(id)
  if (d?.rechargeTenantId != null) d.rechargeTenantId = Number(d.rechargeTenantId)
  detail.value = d
}

/** 提交 */
const emit = defineEmits(['success'])
const onSubmit = async () => {
  await formRef.value.validate()
  try {
    await message.confirm('是否确认充值该密钥？', '提示')
  } catch {
    return
  }
  submitting.value = true
  try {
    await SecretAccountApi.rechargeSecretAccount({
      id: currentId.value as number,
      rechargeAmount: Number(formData.amount),
      remark: formData.remark?.trim() || undefined
    })
    message.success('充值成功')
    dialogVisible.value = false
    emit('success')
  } finally {
    submitting.value = false
  }
}

/** 重置 */
const reset = () => {
  formData.amount = undefined
  formData.remark = undefined
  detail.value = null
}

/** 对外暴露：与新增/编辑同一风格 */
const open = async (_type: string, id?: number) => {
  if (!id) return
  currentId.value = id
  dialogTitle.value = '充值'
  reset()
  dialogVisible.value = true
  await Promise.all([loadTenants(), loadDetail(id)])
}
defineExpose({ open })
</script>
